<template>
  <div class="formula-management-page">
    <div class="page-header">
      <h1>工资计算与公式管理系统</h1>
    </div>
    
    <!-- 选项卡导航 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="公式模板管理" name="template">
        <div class="template-management">
          <div class="template-header">
            <h2>公式模板管理</h2>
            <el-button type="primary" @click="addTemplate">新增公式模板</el-button>
          </div>
          
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column type="index" label="#" width="50"></el-table-column>
            <el-table-column label="模板名称" prop="templateName"></el-table-column>
            <el-table-column label="关联部门" prop="relatedDepartment"></el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="text" size="small" @click="editTemplate(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="deleteTemplate(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="计费类型" width="100">
              <template #default="scope">
                {{ scope.row.chargeType }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="公式编辑器" name="editor">
        <div class="formula-editor">
          <div class="editor-header">
            <h2>公式编辑器</h2>
            <el-button type="text" size="small" @click="switchToTemplate">返回模板管理</el-button>
          </div>
          
          <div class="formula-info">
            <div class="formula-title">公式模板编辑 - {{ currentTemplate.templateName || '新模板' }}</div>
            <el-form :model="currentTemplate" label-width="100px">
              <el-form-item label="模板名称">
                <el-input v-model="currentTemplate.templateName"></el-input>
              </el-form-item>
              <el-form-item label="关联部门">
                <el-select v-model="currentTemplate.relatedDepartment">
                  <el-option label="包装部" value="包装部"></el-option>
                  <el-option label="成型部" value="成型部"></el-option>
                  <el-option label="装配部" value="装配部"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="计费类型">
                <el-radio-group v-model="currentTemplate.chargeType">
                  <el-radio label="计时">计时</el-radio>
                  <el-radio label="计件">计件</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="公式描述">
                <el-input v-model="currentTemplate.formulaDesc"></el-input>
              </el-form-item>
            </el-form>
          </div>
          
          <div class="factor-lists">
            <div class="available-factors">
              <div>可用因子列表</div>
              <el-input placeholder="搜索因子..." v-model="searchFactor"></el-input>
              <el-table :data="filteredAvailableFactors" border size="small">
                <el-table-column prop="name" label="因子名称"></el-table-column>
                <el-table-column prop="unit" label="单位"></el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button type="text" size="mini" @click="addFactor(scope.row)">添加</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <div class="selected-factors">
              <div>已选因子列表</div>
              <div class="factor-actions">
                <el-button type="text" size="small" @click="moveFactorUp" :disabled="selectedFactors.length <= 1 || selectedIndex === 0">
                  [↑] 上移
                </el-button>
                <el-button type="text" size="small" @click="moveFactorDown" :disabled="selectedFactors.length <= 1 || selectedIndex === selectedFactors.length - 1">
                  [↓] 下移
                </el-button>
                <el-button type="text" size="small" @click="removeFactor" :disabled="selectedIndex === -1">
                  [×] 删除
                </el-button>
              </div>
              <el-table :data="selectedFactors" border size="small" @row-click="selectFactor">
                <el-table-column type="index" label="#" width="40"></el-table-column>
                <el-table-column prop="name" label="因子名称"></el-table-column>
                <el-table-column prop="unit" label="单位"></el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button type="text" size="mini" @click="editFactor(scope.row)">编辑</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          
          <div class="formula-expression">
            <div>公式表达式</div>
            <el-input v-model="formulaExpression" type="textarea" rows="4"></el-input>
            <el-button type="text" size="small" @click="openFormulaBuilder"> [公式构建器] </el-button>
          </div>
          
          <div class="formula-preview">
            <div>公式预览</div>
            <div class="preview-content">
              <span>{{ formulaPreview }}</span>
            </div>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" @click="saveTemplate"> [保存模板] </el-button>
            <el-button type="text" @click="resetTemplate"> [重置] </el-button>
            <el-button type="text" @click="cancelEdit"> [取消] </el-button>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="工资计算" name="salary">
        <div class="salary-calculation">
          <div class="salary-header">
            <h2>工资计算</h2>
            <el-button type="text" size="small" @click="switchToTemplate">返回模板管理</el-button>
          </div>
          
          <div class="calculation-form">
            <el-form :model="calculationForm" label-width="120px">
              <el-form-item label="员工姓名">
                <el-input v-model="calculationForm.employee"></el-input>
              </el-form-item>
              
              <el-form-item label="部门">
                <el-select v-model="calculationForm.department">
                  <el-option label="包装部" value="包装部"></el-option>
                  <el-option label="成型部" value="成型部"></el-option>
                  <el-option label="装配部" value="装配部"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="公式模板">
                <el-select v-model="calculationForm.templateId" @change="onTemplateChange">
                  <el-option 
                    v-for="template in tableData" 
                    :key="template.id" 
                    :label="template.templateName" 
                    :value="template.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="计算周期">
                <el-date-picker
                  v-model="calculationForm.period"
                  type="month"
                  format="yyyy-MM"
                  value-format="yyyy-MM"
                  placeholder="选择月份"
                ></el-date-picker>
              </el-form-item>
            </el-form>
          </div>
          
          <div class="parameter-section">
            <h3>计算参数</h3>
            <el-form :model="calculationParams" label-width="150px">
              <el-form-item 
                v-for="(param, index) in currentTemplateFactors" 
                :key="index" 
                :label="param.name + '(' + param.unit + ')'"
              >
                <el-input v-model.number="calculationParams[param.name]"></el-input>
              </el-form-item>
            </el-form>
          </div>
          
          <div class="calculation-actions">
            <el-button type="primary" @click="calculateSalary">计算工资</el-button>
            <el-button type="text" @click="resetCalculation">重置</el-button>
          </div>
          
          <div class="result-section" v-if="calculationResult !== null">
            <h3>计算结果</h3>
            <div class="result-value">
              {{ calculationResult.toFixed(2) }} 元
            </div>
            <div class="result-details">
              <p>计算公式: {{ currentTemplate.formula || '未设置' }}</p>
              <p>计算时间: {{ new Date().toLocaleString() }}</p>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'template',
      tableData: [
        {
          templateName: '包装部计时组公式',
          relatedDepartment: '包装部',
          chargeType: '计时',
          id: 1,
          formulaDesc: '适用于包装部计时工资计算',
          factors: [
            { name: '工作时间', unit: '小时' },
            { name: '基本工资', unit: '元/小时' },
            { name: '加班系数', unit: '倍' }
          ],
          formula: '工作时间 * 基本工资 * (1 + 加班系数)'
        },
        {
          templateName: '成型部自动机公式',
          relatedDepartment: '成型部',
          chargeType: '计件',
          id: 2,
          formulaDesc: '适用于成型部自动机计件工资计算',
          factors: [
            { name: '产量', unit: '件' },
            { name: '单价', unit: '元/件' },
            { name: '良品率', unit: '%' }
          ],
          formula: '产量 * 单价 * 良品率 / 100'
        }
      ],
      availableFactors: [
        { name: '工作时间', unit: '小时' },
        { name: '基本工资', unit: '元/小时' },
        { name: '加班系数', unit: '倍' },
        { name: '产量', unit: '件' },
        { name: '单价', unit: '元/件' },
        { name: '良品率', unit: '%' },
        { name: '绩效系数', unit: '倍' },
        { name: '难度系数', unit: '倍' },
        { name: '工作天数', unit: '天' }
      ],
      selectedFactors: [],
      searchFactor: '',
      selectedIndex: -1,
      currentTemplate: {
        id: null,
        templateName: '',
        relatedDepartment: '',
        chargeType: '计时',
        formulaDesc: '',
        factors: [],
        formula: ''
      },
      formulaExpression: '',
      formulaPreview: '',
      
      // 工资计算相关数据
      calculationForm: {
        employee: '',
        department: '包装部',
        templateId: null,
        period: new Date().toISOString().slice(0, 7)
      },
      calculationParams: {},
      currentTemplateFactors: [],
      calculationResult: null
    };
  },
  computed: {
    filteredAvailableFactors() {
      if (!this.searchFactor) {
        return this.availableFactors.filter(factor => 
          !this.selectedFactors.some(selected => selected.name === factor.name)
        );
      }
      
      return this.availableFactors.filter(factor => 
        factor.name.toLowerCase().includes(this.searchFactor.toLowerCase()) &&
        !this.selectedFactors.some(selected => selected.name === factor.name)
      );
    }
  },
  watch: {
    formulaExpression(newVal) {
      this.formulaPreview = newVal || '暂无公式';
    },
    selectedFactors(newVal) {
      // 当选择的因子变化时，更新公式表达式
      this.updateFormulaExpression();
    },
    activeTab(newTab) {
      // 当切换到工资计算页面时，初始化相关数据
      if (newTab === 'salary') {
        this.initCalculation();
      }
    }
  },
  methods: {
    handleTabClick(tab) {
      // 处理选项卡切换逻辑
      if (tab.name === 'template') {
        this.resetTemplate();
      } else if (tab.name === 'editor') {
        // 编辑器页面可能需要初始化某些数据
      } else if (tab.name === 'salary') {
        this.initCalculation();
      }
    },
    
    switchToTemplate() {
      this.activeTab = 'template';
      this.resetTemplate();
    },
    
    editTemplate(row) {
      // 编辑模板
      this.currentTemplate = { ...row, factors: [...row.factors] };
      this.selectedFactors = [...row.factors];
      this.formulaExpression = row.formula || '';
      this.activeTab = 'editor';
    },
    
    deleteTemplate(row) {
      // 删除模板
      this.$confirm('确定要删除该模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.tableData.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.tableData.splice(index, 1);
          this.$message.success('删除成功');
        }
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    addTemplate() {
      // 新增模板
      this.currentTemplate = {
        id: null,
        templateName: '',
        relatedDepartment: '',
        chargeType: '计时',
        formulaDesc: '',
        factors: [],
        formula: ''
      };
      this.selectedFactors = [];
      this.formulaExpression = '';
      this.activeTab = 'editor';
    },
    
    addFactor(factor) {
      // 添加因子到已选列表
      this.selectedFactors.push({ ...factor });
      this.searchFactor = '';
    },
    
    removeFactor() {
      // 从已选列表中删除因子
      if (this.selectedIndex !== -1) {
        this.selectedFactors.splice(this.selectedIndex, 1);
        this.selectedIndex = -1;
      }
    },
    
    moveFactorUp() {
      // 上移因子
      if (this.selectedIndex > 0) {
        [this.selectedFactors[this.selectedIndex], this.selectedFactors[this.selectedIndex - 1]] = 
        [this.selectedFactors[this.selectedIndex - 1], this.selectedFactors[this.selectedIndex]];
        this.selectedIndex--;
      }
    },
    
    moveFactorDown() {
      // 下移因子
      if (this.selectedIndex < this.selectedFactors.length - 1) {
        [this.selectedFactors[this.selectedIndex], this.selectedFactors[this.selectedIndex + 1]] = 
        [this.selectedFactors[this.selectedIndex + 1], this.selectedFactors[this.selectedIndex]];
        this.selectedIndex++;
      }
    },
    
    selectFactor(row, event, column) {
      // 选择因子
      this.selectedIndex = this.selectedFactors.findIndex(factor => factor.name === row.name);
    },
    
    editFactor(factor) {
      // 编辑因子
      this.$prompt('请输入新的因子名称和单位 (格式: 名称,单位)', '编辑因子', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: `${factor.name},${factor.unit}`
      }).then(({ value }) => {
        const [name, unit] = value.split(',');
        if (name && unit) {
          const index = this.selectedFactors.findIndex(f => f.name === factor.name);
          if (index !== -1) {
            this.selectedFactors[index] = { name: name.trim(), unit: unit.trim() };
          }
        }
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    openFormulaBuilder() {
      // 打开公式构建器
      this.$alert('公式构建器功能待实现', '提示', {
        confirmButtonText: '确定'
      });
    },
    
    updateFormulaExpression() {
      // 根据选择的因子更新公式表达式
      if (this.selectedFactors.length === 0) {
        this.formulaExpression = '';
        return;
      }
      
      // 简单示例：使用所有因子构建一个基本公式
      if (!this.formulaExpression) {
        this.formulaExpression = this.selectedFactors
          .map(factor => factor.name)
          .join(' + ');
      }
    },
    
    saveTemplate() {
      // 保存模板
      if (!this.currentTemplate.templateName) {
        this.$message.warning('请输入模板名称');
        return;
      }
      
      if (this.selectedFactors.length === 0) {
        this.$message.warning('请至少选择一个因子');
        return;
      }
      
      if (!this.formulaExpression) {
        this.$message.warning('请输入公式表达式');
        return;
      }
      
      const templateToSave = {
        ...this.currentTemplate,
        factors: [...this.selectedFactors],
        formula: this.formulaExpression
      };
      
      if (templateToSave.id) {
        // 更新现有模板
        const index = this.tableData.findIndex(item => item.id === templateToSave.id);
        if (index !== -1) {
          this.tableData.splice(index, 1, templateToSave);
        }
      } else {
        // 新增模板
        templateToSave.id = Date.now(); // 简单生成ID
        this.tableData.push(templateToSave);
      }
      
      this.$message.success('保存成功');
      this.activeTab = 'template';
    },
    
    resetTemplate() {
      // 重置模板编辑状态
      this.currentTemplate = {
        id: null,
        templateName: '',
        relatedDepartment: '',
        chargeType: '计时',
        formulaDesc: '',
        factors: [],
        formula: ''
      };
      this.selectedFactors = [];
      this.formulaExpression = '';
      this.selectedIndex = -1;
    },
    
    cancelEdit() {
      // 取消编辑
      this.$confirm('确定要取消编辑吗？未保存的更改将丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.activeTab = 'template';
        this.resetTemplate();
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    // 工资计算相关方法
    initCalculation() {
      // 初始化工资计算页面
      this.calculationForm = {
        employee: '',
        department: '包装部',
        templateId: this.tableData.length > 0 ? this.tableData[0].id : null,
        period: new Date().toISOString().slice(0, 7)
      };
      
      this.currentTemplateFactors = [];
      this.calculationParams = {};
      this.calculationResult = null;
      
      // 如果有模板，加载第一个模板的因子
      if (this.tableData.length > 0) {
        this.onTemplateChange(this.tableData[0].id);
      }
    },
    
    onTemplateChange(templateId) {
      // 当选择的公式模板变化时，更新计算参数
      const template = this.tableData.find(t => t.id === templateId);
      if (template) {
        this.currentTemplate = { ...template };
        this.currentTemplateFactors = [...template.factors];
        
        // 初始化计算参数
        this.calculationParams = {};
        template.factors.forEach(factor => {
          // 根据单位设置默认值
          if (factor.unit === '小时') {
            this.calculationParams[factor.name] = 160;
          } else if (factor.unit === '元/小时') {
            this.calculationParams[factor.name] = 20;
          } else if (factor.unit === '倍') {
            this.calculationParams[factor.name] = 1.5;
          } else if (factor.unit === '件') {
            this.calculationParams[factor.name] = 1000;
          } else if (factor.unit === '元/件') {
            this.calculationParams[factor.name] = 1;
          } else if (factor.unit === '%') {
            this.calculationParams[factor.name] = 95;
          } else {
            this.calculationParams[factor.name] = 0;
          }
        });
      }
    },
    
    calculateSalary() {
      // 验证必要信息
      if (!this.calculationForm.employee) {
        this.$message.warning('请输入员工姓名');
        return;
      }
      
      if (!this.calculationForm.templateId) {
        this.$message.warning('请选择公式模板');
        return;
      }
      
      // 验证所有参数都已填写
      for (const key in this.calculationParams) {
        if (this.calculationParams[key] === null || this.calculationParams[key] === '') {
          this.$message.warning(`请输入${key}`);
          return;
        }
      }
      
      try {
        // 构建计算环境
        const context = {};
        for (const key in this.calculationParams) {
          context[key] = parseFloat(this.calculationParams[key]);
        }
        
        // 使用函数动态计算（简化版，实际项目中可能需要更安全的表达式计算库）
        const formula = this.currentTemplate.formula;
        if (!formula) {
          this.$message.warning('公式模板未设置计算公式');
          return;
        }
        
        // 创建一个安全的计算函数
        const calculateFunction = new Function(...Object.keys(context), `return ${formula};`);
        this.calculationResult = calculateFunction(...Object.values(context));
        
        // 显示计算成功消息
        this.$message.success('计算成功');
        
      } catch (error) {
        console.error('计算出错:', error);
        this.$message.error('计算出错，请检查公式或参数');
        this.calculationResult = null;
      }
    },
    
    resetCalculation() {
      // 重置计算
      this.calculationParams = {};
      this.currentTemplateFactors.forEach(factor => {
        // 重置为默认值
        if (factor.unit === '小时') {
          this.calculationParams[factor.name] = 160;
        } else if (factor.unit === '元/小时') {
          this.calculationParams[factor.name] = 20;
        } else if (factor.unit === '倍') {
          this.calculationParams[factor.name] = 1.5;
        } else if (factor.unit === '件') {
          this.calculationParams[factor.name] = 1000;
        } else if (factor.unit === '元/件') {
          this.calculationParams[factor.name] = 1;
        } else if (factor.unit === '%') {
          this.calculationParams[factor.name] = 95;
        } else {
          this.calculationParams[factor.name] = 0;
        }
      });
      this.calculationResult = null;
    }
  }
};
</script>

<style scoped>
.formula-management-page {
  padding: 20px;
}
.page-header {
  text-align: center;
  margin-bottom: 20px;
}
.template-management,
.formula-editor,
.salary-calculation {
  background-color: #fff;
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.template-header,
.editor-header,
.salary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.factor-lists {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.available-factors,
.selected-factors {
  width: 49%;
}
.factor-actions {
  display: flex;
  margin-bottom: 10px;
}
.preview-content {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  min-height: 40px;
  word-break: break-all;
}
.action-buttons,
.calculation-actions {
  margin-top: 20px;
  text-align: center;
}
.parameter-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 5px;
}
.result-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #e8f5e9;
  border-radius: 5px;
}
.result-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}
.result-details {
  color: #666;
}
</style>